//
//  SDContactsTableViewController.m
//  GSD_WeiXin(wechat)
//
//  Created by aier on 16/2/10.
//  Copyright © 2016年 GSD. All rights reserved.
//
//当前展示状态
typedef enum{
    //以下是枚举成员
    CurrentTypeAll = 0,//总数据展示
    CurrentTypeSearch = 1, //筛选数据展示
    
}CurrentType;


#import "SDContactsTableViewController.h"
#import "SDContactModel.h"
#import "SDContactsTableViewCell.h"
#import "HQConversationViewController.h"
#import "HomeStrangCollionViewController.h"

@interface SDContactsTableViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
@property (nonatomic,strong) NSArray * dataSource;

@property (nonatomic, strong) NSMutableArray *dataArray;//总数据

@property (nonatomic,strong) NSArray * currentArr;// *  当前搜索到的用户数组

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic, strong) NSMutableArray *sectionArray;

@property (nonatomic, strong) NSMutableArray *sectionTitlesArray;

@property (nonatomic,  weak ) UIView *navBarView;

@property (nonatomic, strong) NSString *deleteWid;

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic,assign) CurrentType currentType;

@property (nonatomic,strong) NSString * searchText;//搜索字符


@end

@implementation SDContactsTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
}
//返回
- (void)backAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName : FontP(18)};
    self.navigationController.navigationBar.barTintColor = Colorbackground;
    [self.navigationController.navigationBar setTranslucent:NO];
    [self setTitle:@"通讯录"];
    [self sendRequest];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}
- (void)genDataWithArray:(NSArray *)array {
    for (int i = 0; i < array.count; i++) {
        NSDictionary *dic = array[i];
        SDContactModel *model = [SDContactModel new];
        model.name = dic[@"nickName"];
        model.imageName = dic[@"photo"];
        model.wid = dic[@"wid"];
        [self.dataArray addObject:model];
    }
    [self setUpTableSection];
}

- (void)setUpTableSection {
        UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
        NSUInteger numberOfSections = [[collation sectionTitles] count];
        NSMutableArray *newSectionArray =  [[NSMutableArray alloc]init];
        for (NSUInteger index = 0; index<numberOfSections; index++) {
            [newSectionArray addObject:[[NSMutableArray alloc]init]];
        }
        for (SDContactModel *model in self.dataArray) {
            NSUInteger sectionIndex = [collation sectionForObject:model collationStringSelector:@selector(name)];
            [newSectionArray[sectionIndex] addObject:model];
        }
        for (NSUInteger index=0; index<numberOfSections; index++) {
            NSMutableArray *personsForSection = newSectionArray[index];
            NSArray *sortedPersonsForSection = [collation sortedArrayFromArray:personsForSection collationStringSelector:@selector(name)];
            newSectionArray[index] = sortedPersonsForSection;
        }
        NSMutableArray *temp = [NSMutableArray new];
        self.sectionTitlesArray = [NSMutableArray new];
        [newSectionArray enumerateObjectsUsingBlock:^(NSArray *arr, NSUInteger idx, BOOL *stop) {
            if (arr.count == 0) {
                [temp addObject:arr];
            } else {
                [self.sectionTitlesArray addObject:[collation sectionTitles][idx]];
            }
        }];
        [newSectionArray removeObjectsInArray:temp];
        self.sectionArray = newSectionArray;
    
        //搜索
    UISearchBar *searchBar = [[UISearchBar alloc]init];
    searchBar.frame = CGRectMake(0, 0, KScreenWidth, 50);
    searchBar.barStyle     = UIBarStyleBlackOpaque;
    searchBar.translucent  = YES;
    searchBar.delegate     = self;
    
    searchBar.keyboardType = UIKeyboardTypeDefault;
    searchBar.placeholder = @"搜姓名";
    
     UIImage * image = [self createImageWithColor:ColorI(0xefeff4)];

    
    image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
    
    searchBar.backgroundImage = image;
    searchBar.backgroundColor = [UIColor clearColor];
    UIView *searchTextField = [[[searchBar.subviews firstObject] subviews] lastObject];
    searchTextField.backgroundColor = ColorI(0xffffff);
    
    searchTextField.layer.cornerRadius = 15;
    searchTextField.clipsToBounds = YES;
    _searchBar = searchBar;
    
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        _tableView.sectionIndexColor = [UIColor blackColor];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(self.view).offset(0);
        }];
    
        [_tableView setTableHeaderView:_searchBar];

        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView reloadData];
}
// 开始编辑搜索内容时
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    [searchBar setShowsCancelButton:YES animated:YES];
    
    return YES;
}
// 点击搜索栏的取消键时
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
    
    if (self.currentType == CurrentTypeSearch) {
        self.currentType = CurrentTypeAll;
    }
    
    searchBar.text = nil;
    self.searchText = nil;
    _dataArray = [NSMutableArray arrayWithArray:self.dataSource];
    [self.tableView reloadData];
    
}
// 点击搜索按钮时
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar setShowsCancelButton:NO animated:YES];
    [self.searchBar resignFirstResponder];
    
}
/**
 *  文字发生改变时调用
 */
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    if (self.currentType == CurrentTypeAll) {
        self.currentType = CurrentTypeSearch;
    }
    
    if (searchText .length == 0) {
        
        self.searchText = nil;
        self.currentType = CurrentTypeAll;
        self.dataSource = self.dataArray;
        
        [self.tableView reloadData];
    }else{
        
        //将搜索的字符转化为字母并赋值
        self.searchText = [self transform:searchText];
        
        //搜索数组
        self.currentArr = [self searchArrWithText:searchText];
        
        
        self.dataSource = self.currentArr;
        
        //刷新数组
        [self.tableView reloadData];
    }
    
}
/**
 *  搜索数组
 */
- (NSArray *)searchArrWithText:(NSString *)text{
    
    
    NSMutableArray * finalArr = [NSMutableArray array];
    for (SDContactModel * model in _dataArray) {
        
        //当前model的姓名拼音
        
        if (model.name) {
            NSString * name = [self transform:model.name];
            NSString * searchText = [self transform:text];
            
            NSRange strRan = [name rangeOfString:searchText];
            
            if (strRan.length > 0) {
                [finalArr addObject:model];
            }
        }
        
        
    }
    
    return finalArr;
}

/**
 *  汉字转拼音
 */
- (NSString *)transform:(NSString *)chinese{
    
    NSMutableString *pinyin = [chinese mutableCopy];
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    
    return [pinyin uppercaseString];
}


/**
 *  UIColor转化为UIImage
 */
- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0,0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}
#pragma mark =================tableview delegate and datasource===============
//点击cell收回键盘
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_searchBar resignFirstResponder];
    return indexPath;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ( self.currentType == CurrentTypeSearch) {
        return self.dataSource.count;
    }else{
        return self.sectionTitlesArray.count;

    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if ( self.currentType == CurrentTypeSearch) {
        return self.dataSource.count;
    }else{
        return [self.sectionArray[section] count];
        
    }

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"SDContacts";
    SDContactsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[SDContactsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    SDContactModel *model = self.sectionArray[section][row];
    cell.model = model;
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
        
    
        return [self.sectionTitlesArray objectAtIndex:section];
        
    
}

//右边通讯录姓名展示条
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.sectionTitlesArray;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%ld",(long)indexPath.row);
    NSLog(@"%ld",indexPath.section);
    
    SDContactModel *model = self.sectionArray[indexPath.section][indexPath.row];
//    if (indexPath.section == 0) {
//        if (indexPath.row == 0) {
//            HRNewFriendViewController *NFVC = [[HRNewFriendViewController alloc] init];
//            [self.navigationController pushViewController:NFVC animated:YES];
//        }
//        if (indexPath.row == 1) {
//            HRGroupViewController *NFVC = [[HRGroupViewController alloc] init];
//            [self.navigationController pushViewController:NFVC animated:YES];
//        }
//    } else {
//        HRUserDetailInfoViewController *UDIVC = [[HRUserDetailInfoViewController alloc] init];
//        UDIVC.uid = model.wid.integerValue;
//        [self.navigationController pushViewController:UDIVC animated:YES];
//        HQConversationViewController *conversationVC = [[HQConversationViewController alloc]init];
//        conversationVC.conversationType = ConversationType_PRIVATE;
//        conversationVC.targetId = model.wid.stringValue;
//        conversationVC.title = model.name;
//        conversationVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:conversationVC animated:YES];

 
    
    HomeStrangCollionViewController *UDIVC = [[HomeStrangCollionViewController alloc] init];
    UDIVC.navigationController.navigationBar.hidden = YES;
    UDIVC.UserId = [NSString stringWithFormat:@"%ld",(long)model.wid.integerValue] ;
    [self.navigationController pushViewController:UDIVC animated:YES];
    
}

//删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSUInteger section = indexPath.section;
    NSUInteger row = indexPath.row;
    
    NSMutableArray *delArray = [[NSMutableArray alloc]initWithArray:[self.sectionArray objectAtIndex:section]];
    
    SDContactModel *model = [delArray objectAtIndex:row];
    self.deleteWid = [NSString stringWithFormat:@"%@",model.wid];
    [delArray removeObjectAtIndex:row];
    [self.sectionArray replaceObjectAtIndex:indexPath.section withObject:delArray];
    
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    
    [self deleteCellPeopleRequest];
}
//删除cell时展示
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

{
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}



#pragma mark ========================数据请求=====================
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    return _dataArray;
}
//通讯录请求方法
- (void)sendRequest {
    WEAKSELF
    [HQHttpManager myFriendListWithUserid:[HQHttpManager getUserId] successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            [weakSelf.dataArray removeAllObjects];
            [weakSelf.sectionArray removeAllObjects];
            [weakSelf.sectionTitlesArray removeAllObjects];
            NSArray *array = resultDic[@"res"];
            [weakSelf genDataWithArray:array];
        }
    }];
}
//删除方法
-(void)deleteCellPeopleRequest{
    [HQHttpManager deleteFriendListWithUserid:[HQHttpManager getUserId] andWid:self.deleteWid successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
        if (isSuccess) {
            [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_PRIVATE targetId:self.deleteWid];
            [[RCIMClient sharedRCIMClient] clearMessages:ConversationType_PRIVATE targetId:self.deleteWid];
            [self sendRequest];
        }else{
            //删除失败
        }
    }];
}


@end
